import {_decorator, Component, lerp, Node, Vec3} from 'cc';
import {BaseInfo} from "db://assets/scripts/data/model/BaseInfo";
import {AudioManager} from "db://assets/scripts/common/AudioManager";
import {GameManager} from "db://assets/scripts/game/GameManager";
import {PoolManager} from "db://assets/scripts/common/PoolManager";
import {EffectManager} from "db://assets/scripts/common/EffectManager";
import {Skill} from "db://assets/scripts/data/model/Skill";
import {AudioPaths} from "db://assets/scripts/common/AudioPaths";
import {MonsterController} from "db://assets/scripts/game/role/monster/MonsterController";
import {GameState} from "db://assets/scripts/game/GameState";

const {ccclass, property} = _decorator;

/**
 * 能量球脚本: 直线飞行
 */
@ccclass('EnergyBallEffect')
export class EnergyBallEffect extends Component {
    /**
     * 敌人基本信息
     */
    public baseInfo: any = null!;
    /**
     * 技能信息
     */
    public skillInfo: any = null!;

    /**
     * 当前速度
     */
    private curSpeed: number = 0;
    /**
     * 目标速度
     */
    private targetSpeed: number = 0;
    /**
     * 和玩家之间的向量差
     */
    private offsetPos: Vec3 = new Vec3();
    /**
     * 当前节点世界坐标
     */
    private curWorPos: Vec3 = new Vec3();
    /**
     * 能量球节点超过玩家这个范围则隐藏
     */
    private disappearRange: number = 25;
    /**
     * 能量球的下次目标位置
     */
    private targetWorPos: Vec3 = new Vec3();

    start() {
        // [3]
    }

    /**
     * 初始化
     *
     * @param skillInfo 技能信息
     * @param baseInfo 基础信息
     * @param parentScript 使用者
     */
    public init(skillInfo: Skill, baseInfo: BaseInfo, parentScript: MonsterController) {
        this.skillInfo = skillInfo;
        this.baseInfo = baseInfo;
        parentScript.warningScript?.hideWarning();
        this.targetSpeed = skillInfo.speed;

        this.curSpeed = skillInfo.speed * 0.5;

        EffectManager.getInstance().playParticle(this.node);

        AudioManager.getInstance().playSound(AudioPaths.energyBallSound);
    }

    update(deltaTime: number) {
        if (!this.node.parent
            || !GameManager.getInstance().gamePlayerProxy.getPlayerNode()
            || GameManager.getInstance().gameStateProxy.getGameState() === GameState.OVER
            || GameManager.getInstance().gameStateProxy.getGameState() === GameState.PAUSE) {
            return;
        }

        //朝forward方向飞行
        this.curSpeed = lerp(this.targetSpeed, this.curSpeed, 0.25);
        this.targetWorPos.set(0, 0, -deltaTime * this.curSpeed);
        this.node.translate(this.targetWorPos, Node.NodeSpace.LOCAL);
        this.curWorPos.set(this.node.worldPosition);

        //超过玩家一定范围则隐藏
        Vec3.subtract(this.offsetPos, this.curWorPos, GameManager.getInstance().gamePlayerProxy.getPlayerNode().worldPosition);
        if (this.offsetPos && this.offsetPos.length() >= this.disappearRange) {
            PoolManager.getInstance().putNode(this.node);
        }
    }
}